<?php
namespace captcha;
use \think\{Cache};
use \think\captcha\Captcha as think_captcha;
class Captcha{
    protected $options = [
        // 驱动方式
        'type'   => 'File',
        // 缓存保存目录
        'path'   => CACHE_PATH.'captcha'.DS,
        // 缓存前缀
        'prefix' => '',
        // 缓存有效期 0表示永久缓存
        'expire' => 3600,
    ];

    public function __construct($options=[]){
        $today = date('Ymd',time());
        $this->options['path'] = $this->options['path'].$today.DS;
        $this->options = $options+$this->options;
        Cache::connect($this->options);
    }

    /**
     * 创建验证码
     * @param  string  $guid      [description]
     * @param  integer $code_len  [description]
     * @param  integer $code_type [description]
     * @return [type]             [description]
     */
    public function create($guid='',$code_len=4,$code_type=1)
    {
        $guid = $guid?:implode('',explode('.',uniqid(mt_rand(), true)));
        $code_info = [
            'verify_code' => rand_string($code_len,$code_type),
            'expire_time' => time()+$this->options['expire']
        ];
        $rs = Cache::set($guid,$code_info);
        return ['guid'=>$guid,'code'=>$code_info['verify_code']];
    }

    /**
     * 检测验证码
     * @param  [type] $code [description]
     * @param  [type] $guid [description]
     * @return [type]       [description]
     */
    public function check($code, $guid)
    {
        //错误标识
        //1:验证通过
        //0:错误
        //-1:过期
        $code_info = Cache::get($guid);
        $rs = -1;
        //验证码是否过期
        if(!is_null($code_info)){
            if(time()-$code_info['expire_time']<0){
                if(strtoupper($code) != $code_info['verify_code']){
                    return 0;
                }
                $rs = 1;
            }
            Cache::rm($guid);
        }
        return $rs;
    }

    public function test(){
        $a = new think_captcha();
        print_r($a->entry());
    }
}